package com.centit.framework.ip.businessdata.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.centit.framework.ip.businessdata.dao.MessageInfoDao;
import com.centit.framework.ip.businessdata.po.MessageInfo;
import com.centit.framework.ip.businessdata.service.MessageInfoManager;
import com.centit.framework.jdbc.dao.DatabaseOptUtils;
import com.centit.framework.jdbc.service.BaseEntityManagerImpl;
import com.centit.framework.model.basedata.IOptInfo;
import com.centit.framework.system.dao.OptInfoDao;
import com.centit.framework.system.po.OptInfo;
import com.centit.framework.system.service.OptInfoManager;
import com.centit.support.database.utils.PageDesc;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * MessageInfo  Service.
 * create by scaffold 2018-06-04
 *
 * @author guo_jh
 * T_MESSAGE_INFO支撑平台消息数据表
 */
@Service
public class MessageInfoManagerImpl
        extends BaseEntityManagerImpl<MessageInfo, String, MessageInfoDao>
        implements MessageInfoManager {

    public static final Log log = LogFactory.getLog(MessageInfoManager.class);


    private MessageInfoDao messageInfoDao;

    @Resource(name = "messageInfoDao")
    @NotNull
    public void setMessageInfoDao(MessageInfoDao baseDao) {
        this.messageInfoDao = baseDao;
        setBaseDao(this.messageInfoDao);
    }
    @Resource
    private OptInfoDao optInfoDao;
    /*
         @PostConstruct
        public void init() {

        }

     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public JSONArray listMessageInfosAsJson(
            String[] fields,
            Map<String, Object> filterMap, PageDesc pageDesc) {

        return null;
    }

    @Override
    public void updateBysql(String sql, Object[]param) {
        DatabaseOptUtils.doExecuteSql(baseDao,sql,param);
    }

    @Override
    public List<OptInfo> listOptId( String userCode, String superOptId,boolean asAdmin ,String module,String currOptid) {
        List<OptInfo> preOpts=optInfoDao .getMenuFuncByOptUrl();
        String optType = asAdmin ? "S" : "O";
        List<OptInfo> ls=optInfoDao.getMenuFuncByUserID(userCode, optType);
        List<OptInfo> menuFunsByUser = getMenuFuncs(preOpts,  ls);
        return formatMenuTree(menuFunsByUser,superOptId,currOptid);
      /*
        List<OptInfo> info=new ArrayList<OptInfo>();
        OptInfo optInfo=optInfoManager.getObjectById(optId);
        info.add(optInfo);
        return info;*/
    }
    public static List<OptInfo> getMenuFuncs(List<OptInfo> preOpts, List<OptInfo> ls) {
        boolean isNeeds[] = new boolean[preOpts.size()];
        for (int i = 0; i < preOpts.size(); i++) {
            isNeeds[i] = false;
        }
        List<OptInfo> opts = new ArrayList<>();
        for(OptInfo opt : ls){
            opts.add(opt);
            for (int i = 0; i < preOpts.size(); i++) {
                if (opt.getPreOptId() != null && opt.getPreOptId().equals(preOpts.get(i).getOptId())) {
                    isNeeds[i] = true;
                    break;
                }
            }
        }

        List<OptInfo> needAdd = new ArrayList<>();
        for (int i = 0; i < preOpts.size(); i++) {
            if (isNeeds[i]) {
                needAdd.add(preOpts.get(i));
            }
        }

        boolean isNeeds2[] = new boolean[preOpts.size()];
        while (true) {
            int nestedMenu = 0;
            for (int i = 0; i < preOpts.size(); i++) {
                isNeeds2[i] = false;
            }
            for (int i = 0; i < needAdd.size(); i++) {
                for (int j = 0; j < preOpts.size(); j++) {
                    if (!isNeeds[j] && needAdd.get(i).getPreOptId() != null
                            && needAdd.get(i).getPreOptId().equals(preOpts.get(j).getOptId())) {
                        isNeeds[j] = true;
                        isNeeds2[j] = true;
                        nestedMenu++;
                        break;
                    }
                }
            }
            if (nestedMenu == 0)
                break;

            needAdd.clear();
            for (int i = 0; i < preOpts.size(); i++) {
                if (isNeeds2[i]) {
                    needAdd.add(preOpts.get(i));
                }
            }

        }

        for (int i = 0; i < preOpts.size(); i++) {
            if (isNeeds[i]) {
                opts.add(preOpts.get(i));
            }
        }
        return opts;
        /*
        CollectionsOpt.sortAsTree(opts, new CollectionsOpt.ParentChild<OptInfo>() {
            @Override
            public boolean parentAndChild(OptInfo p, OptInfo c) {
                return p.getOptId().equals(c.getPreOptId());
            }

        });*/
    }
    /**
     * 将菜单列表组装为树状
     * @param optInfos 菜单列表
     * @param superOptId 顶级菜单ID 不为空时返回该菜单的下级菜单
     * @return 树状菜单列表
     */
    private List<OptInfo> formatMenuTree(List<OptInfo> optInfos,String superOptId,String currOptid) {
        /*if (StringUtils.isEmpty(superOptId)){
            return Collections.emptyList();
        }*/

        Iterator<OptInfo> menus = optInfos.iterator();
        OptInfo parentOpt = null;
        List<OptInfo> menu = new ArrayList<OptInfo>();
        while (menus.hasNext()) {
            OptInfo optInfo = menus.next();
            if (StringUtils.equals(superOptId, optInfo.getOptId())) {
                parentOpt=optInfo;
            }
            for (OptInfo opt : optInfos) {
                if (opt.getOptId().equals(optInfo.getPreOptId())) {
                    opt.addChild(optInfo);
                }
            }
            if(optInfo.getPreOptId().equals("0")) {
            	menu.add(optInfo) ;
            }
        }
        return menu;
        
    }
}

